﻿using Microsoft.Data.SqlClient;
using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace 从数据库中读取配置文件
{
    internal class TxDBConfig : ConfigurationProvider
    {
        public string ConnStr { get; set; }
        public string tableName { get; set; }
        public TxDBConfig(string str,string tableName) { 
            this.ConnStr = str;
            this.tableName = tableName;
        }
        public override void Load()
        {
            base.Load();
            using (SqlConnection conn = new SqlConnection(ConnStr))
            {
                conn.Open();
                string sql = $"select Name,Value from {tableName} where Id in(select Max(Id) from {tableName} group by Name)";
                using (SqlCommand cmd = conn.CreateCommand())
                {
                    cmd.CommandText = sql;
                    using(SqlDataReader reader = cmd.ExecuteReader())
                    {
                        while (reader.Read())
                        {
                            string name = reader["name"].ToString();
                            string value = reader["value"].ToString();
                            this.Data[name] = value;
                        }
                    }
                }

            }
        }
    }
}
